<?
	// Start session
	session_start();
	$GL_SESSION_ID = session_id();
	if($GL_SESSION_ID = '') {
		$GL_SESSION_ID = session_regenerate_id();
	}
	
	// Setup Db
	require_once('dbController.php');
	require_once('glGlobals.php');

	$glDb = new dbController($DB_CONNECT);

	// Ok, let's go.
	
	$GL_IMAGE_WIDTH = 180;
	
	if(!isset($_REQUEST['rt']) || !isset($_REQUEST['dp']) || !isset($_REQUEST['dg']) || !isset($_REQUEST['u']) || !isset($_REQUEST['rt']) || !isset($_REQUEST['nr']) || !isset($_REQUEST['t']) || !isset($_REQUEST['g']) || !isset($_REQUEST['a'])) {
		die('Game Error:  Game not configured properly');
	}
	$TIMEOUT=500;
	$GL_GAME_ACTION = $_REQUEST['a'];
	$GL_GAME_NAME = $_REQUEST['g'];
	$GL_ROUNDS = $_REQUEST['nr'];
	$GL_USERNAME = $_REQUEST['u'];
	$GL_NUM_DROPS = $_REQUEST['dp'];
	$GL_NUM_DRAGS = $_REQUEST['dg'];
	$GL_ROUND_TIME = $_REQUEST['rt'];
	$GL_QUERY = '';
	if(isset($_REQUEST['q'])) {
		$GL_QUERY = $_REQUEST['q'];
	}
	$GL_TEAM = $_REQUEST['t'];
	
	if($GL_GAME_ACTION == 'new') {
		// Creating a game
		$time = time();
		$SQL = "INSERT INTO gamestate (admin,rounds,roundlength,maximages,maxholders,gamename,gamestart) VALUES ('$GL_USERNAME',$GL_ROUNDS,$GL_ROUND_TIME,$GL_NUM_DRAGS,$GL_NUM_DROPS,'$GL_GAME_NAME',$time)";
		
		$glDb->query($SQL);
		
		$SQL = "SELECT MAX(gameid) FROM gamestate";
		$GL_GAME_ID = $glDb->getOne($SQL);
		
		// Create the first round
		$SQL = "INSERT INTO roundstate (gameid, moveid, roundstarttime, go, userturn) VALUES ($GL_GAME_ID,0,$GL_ROUND_TIME,0,'$GL_USERNAME')";
		$glDb->query($SQL);
	} else {
		// Retrieve the game data!
		$SQL = "SELECT rounds, roundlength, maximages, maxholders, gamename, gameid FROM gamestate WHERE gamename = '$GL_GAME_NAME' ORDER BY gameid DESC";
		$result = $glDb->getRow($SQL);
		$GL_ROUNDS = $result[0];
		$GL_ROUND_TIME = $result[1];
		$GL_NUM_DRAGS = $result[2];
		$GL_NUM_DROPS = $result[3];
		$GL_GAME_NAME = $result[4];
		$GL_GAME_ID = $result[5];
		
	}
	// Create the session for this game
	$SQL = "INSERT INTO gameusers (gameid, username, sessionid, team) VALUES ($GL_GAME_ID,'$GL_USERNAME','$GL_SESSION_ID','$GL_TEAM')";
	$glDb->query($SQL);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Glictionary</title>
<script type="text/javascript" src="lib/jquery-1.2.3.js"></script>
<script type="text/javascript" src="lib/interface.js"></script>
<script type="text/javascript" src="lib/jquery.comet.js"></script>
<script type="text/javascript" src="lib/glictionary.js"></script>

<script type="text/javascript">
GL_IMG_WIDTH = <?=$GL_IMAGE_WIDTH?>;
GL_NUM_DROPS = <?=$GL_NUM_DROPS?>;
GL_NUM_DRAGS = <?=$GL_NUM_DRAGS?>;
GL_USERNAME = '<?=$GL_USERNAME?>';
GL_CURRENT_USER = '';
GL_GAMEID = <?=$GL_GAME_ID?>;
GL_MOVEID = 0;
GL_QUERY = '';
GL_DROPID = '';
GL_DROPSRC = '';
GL_ROUND = '';
GL_WORD = '';

GL_OLDQUERY = '';
GL_OLDDROPID = '';
GL_OLDDROPSRC = '';

imgArray = Array();

$(document).ready(

	function() {
		resizeContentArea(<?=$GL_NUM_DRAGS?>,<?=$GL_IMAGE_WIDTH?>);
		$('#pa').fadeIn(750);
		$('#ma_beginRoundButton').hide();
		$('#ma_clearBoardButton').hide();
		
		for(i=0; i < GL_NUM_DRAGS; i++) {
			$('#drag' + i).Draggable(
				{
					revert:			true
				}
			);
		}

		for(i=0; i < GL_NUM_DROPS; i++) {
			$('#drop' + i).Droppable(
				{
					accept :		'dropaccept', 
					activeclass:	'dropactive', 
					hoverclass:		'drophover',
					tolerance:		'intersect',
					ondrop: function(drag) {
						dragsrc = $('#' + drag.id).html();
						$('#' + this.id).html(dragsrc);
						$('#' + drag.id).html('');
						$.get('sendUpdate.php?gameid=' + GL_GAMEID + '&type=drop&dragid=' + this.id + '&dragsrc=' + dragsrc);
					}
				}
			);		
		}
		timerId = setTimeout("gameLoop()",<?=$TIMEOUT?>);
	}
);

function gameLoop() {
	updateGameData();
	if (GL_QUERY != '' && GL_OLDQUERY != GL_QUERY) {
		loadImages(<?=$GL_NUM_DRAGS?>,GL_QUERY);
		GL_OLDQUERY = GL_QUERY;
	}
	if (GL_DROPID != '' && ((GL_DROPID == GL_OLDDROPID && GL_DROPSRC != GL_OLDDROPSRC) || GL_DROPID != GL_OLDDROPID)) {
		$(GL_DROPID).html(GL_DROPSRC);		
		GL_OLDDROPID = GL_DROPID;
		GL_OLDDROPSRC = GL_DROPSRC;
	}
	timerId = setTimeout("gameLoop()",<?=$TIMEOUT?>);
}

function clearBoard() {
	for(i=0; i < <?=$GL_NUM_DROPS?> && i<imgArray.length; i++) {
		dragid = 'drop' + i;
		$.get('sendUpdate.php?gameid=' + GL_GAMEID + '&type=drop&dragid=' + dragid + '&dragsrc= ');
		$('#drop' +i).html('');
	}
}

function loadImages(numImages,query) {
	// If I'm the current player,
	GL_QUERY = query;
	if(GL_CURRENT_USER == GL_USERNAME) {
		$.get('sendUpdate.php?gameid=' + GL_GAMEID + '&type=query&query=' + query);
	}
	$.get('imgSelect.php?q=' + query  + '%20-' + GL_WORD + '&n=' + numImages,function(data) {
		imgArray = data.split(',');
		for(i=0; i < <?=$GL_NUM_DRAGS?> && i<imgArray.length; i++) {
			$('#drag' + i).html(imgArray[i]);
		}
		if(imgArray.length < <?=$GL_NUM_DRAGS?>) {
			for(i=imgArray.length; i<<?=$GL_NUM_DRAGS?>; i++) {
				if(GL_CURRENT_USER != GL_USERNAME) {
					$('#drag' + i).Draggable(
						{
							revert:			true,
							insideParent:	true
						}
					);
				}
				else {
					$('#drag' + i).Draggable(
						{
							revert:			true
						}
					);			
				}
				$('#drag' + i).html('');
			}
		}
	});
	return false;
}

</script>
<link rel="stylesheet" href="lib/glictionary.css" />
</head>
<body onresize="resizeContentArea(<?=$GL_NUM_DRAGS?>,<?=$GL_IMAGE_WIDTH?>);">
<div id="pa">
  <div id="ga">
    <div id="ga_player_entry">
      <form onsubmit="return loadImages(<?=$GL_NUM_DRAGS?>,document.getElementById('q').value);" style="left:40px; top:9px; position:relative;">
        Google Image Query:
        <input type="text" id="q" value="<?=$GL_QUERY?>"/>
        <input type="submit" value="Go" />
      </form>
    </div>
    <div id="ga_player_board">
      <div id="ga_player_imgSelect">
        <?
  	for($i = 0; $i < $GL_NUM_DRAGS; $i++) {
	  ?>
        <div id="drag<?=$i?>" class="dropaccept">&nbsp;</div>
        <?
  	}
?>
      </div>
    </div>
    <div id="ga_group_board">
      <?
  	for($i = 0; $i < $GL_NUM_DROPS; $i++) {
  ?>
      <div id="drop<?=$i?>" class="dropzone">&nbsp;</div>
      <?
  	}
  ?>
    </div>
    <div id="ga_group_entry">
      <form onsubmit="return submitGuess()" style="left:40px; top:9px; position:relative;">
        Answer:
        <input type="text" id="g" />
        <input type="submit" value="Submit" />
      </form>
    </div>
  </div>
  <div id="ma">
  <img src="image/Googlictionary.jpg" style="border-color:#000000; border:solid; margin-bottom:20px; border-width:1px" />
    <div id="ma_roundTimer">
  	Round Time: <?=$GL_ROUND_TIME?>
  </div>
<p align="center">  <input type="button" id="ma_beginRoundButton" onclick="beginRound()" value="Begin Round"/> <input type="button" id="ma_clearBoardButton" onclick="clearBoard()" value="Clear Board" /> </p>
  <h3>Game Statistics</h3>
  <div id="ma_scoreArea">
	Game: <?=$GL_GAME_NAME?><br />
    Round: 0/<?=$GL_ROUNDS?><br />
    Team A: 0 Points<br />
    Team B: 0 Points</div>
    <h3>Users</h3>
  <div id="ma_userArea">
  	<ul>
	    <li><?=$GL_USERNAME?>
          (Team 
        <?=$GL_TEAM?>)</li>
        
    </ul>
  </div>
  <h3>Current Word</h3>
  <div id="ma_currentWordArea">
  	?
  </div>
  <h3>Guesses</h3>
  <div id="ma_guessArea">
  	?
  </div>
  </div>
</div>
</body>
</html>
